//express_demo.js 文件
var express = require('express'); //引用express
var app = express(); //创建express实例
var path = require('path');
var fs = require('fs');
var userlist = require('./data/user.json');
var textlist = require('./data/list.json');
app.use(express.static(path.join(__dirname, 'public')));
//解析post请求
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    //必须是绝对路径
    res.sendFile(path.join(__dirname, '/views/index.html'));
});
app.get('/add', (req, res) => {
    //必须是绝对路径
    res.sendFile(path.join(__dirname, '/views/add.html'));
});
app.get('/home', (req, res) => {
    //必须是绝对路径
    res.sendFile(path.join(__dirname, '/views/home.html'));
});
app.get('/update', (req, res) => {
    //必须是绝对路径
    res.sendFile(path.join(__dirname, '/views/update.html'));
});
app.get('/homelist', (req, res) => {
    //必须是绝对路径
    res.send(textlist);
});

app.post('/addtext', (req, res) => {
    textlist.push(req.body);
    fs.writeFileSync('./data/list.json', JSON.stringify(textlist));
    res.send({
        code: 1,
        msg: '添加成功',
    });
});
app.post('/updatepwd', (req, res) => {
    let { user, pwd } = req.body;
    userlist.forEach(item => {
        if (item.user == user) {
            item.pwd = pwd;
        }
    });
    fs.writeFileSync('./data/user.json', JSON.stringify(userlist));
    res.send({
        code: 1,
        msg: '修改成功',
    });
});
app.get('/register', (req, res) => {
    //必须是绝对路径
    res.sendFile(path.join(__dirname, '/views/register.html'));
});
app.post('/login', (req, res) => {
    let { user, pwd } = req.body;
    userlist.forEach(item => {
        if (item.user == user && item.pwd == pwd) {
            res.send({
                code: 1,
                msg: '登录成功',
            });
        }
    });
    res.send({
        code: 0,
        msg: '用户名或密码不正确',
    });
});
app.post('/registry', (req, res) => {
    let { user, pwd } = req.body;
    console.log(user);
    let falg = false;
    userlist.forEach(item => {
        if (item.user == user) {
            falg = true;
        }
    });
    if (falg) {
        res.send({
            code: 0,
            msg: '用户名已存在',
        });
    } else {
        userlist.push(req.body);
        fs.writeFileSync('./data/user.json', JSON.stringify(userlist));
        res.send({
            code: 1,
            msg: '注册成功',
        });
    }
});

var server = app.listen(8081);
